package org.example.review.service.impl;

import org.example.review.dto.DepartmentDTO;
import org.example.review.mapper.DepartmentMapper;
import org.example.review.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.logging.Logger;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    private static final Logger logger = Logger.getLogger(DepartmentServiceImpl.class.getName());

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<DepartmentDTO> getDepartments() {
        logger.info("开始获取部门列表");
        try {
            List<DepartmentDTO> allDepartments = departmentMapper.selectDepartmentList();
            List<DepartmentDTO> treeDepartments = buildDepartmentTree(allDepartments);
            logger.info("获取部门列表成功，数量: " + treeDepartments.size());
            return treeDepartments;
        } catch (Exception e) {
            logger.severe("获取部门列表失败: " + e.getMessage());
            throw new RuntimeException("获取部门列表失败: " + e.getMessage());
        }
    }

    private List<DepartmentDTO> buildDepartmentTree(List<DepartmentDTO> departments) {
        if (departments == null || departments.isEmpty()) {
            return new ArrayList<>();
        }

        Map<Integer, List<DepartmentDTO>> groupByParent = departments.stream()
                .filter(dept -> dept.getParentId() != null)
                .collect(Collectors.groupingBy(DepartmentDTO::getParentId));

        departments.forEach(dept -> {
            List<DepartmentDTO> children = groupByParent.get(dept.getId());
            if (children != null) {
                dept.setChildren(children);
            }
        });

        return departments.stream()
                .filter(dept -> dept.getParentId() == null || dept.getParentId() == 0)
                .collect(Collectors.toList());
    }
}
